package com.example.com.common.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;


import javax.security.auth.x500.X500Principal;

public class L {
    public static boolean isDebug = true;
    private static final String DEFAULT_TAG = "APPLogInfo";

    public static void e(final String tag, final String msg) {
        if (isDebug) {
            Log.e(tag, msg);
        }
    }

    public static void e(final String msg) {
        if (isDebug) {
            Log.e(DEFAULT_TAG, msg);
        }
    }

    public static void d(String msg) {
        if (isDebug) {
            Log.d(DEFAULT_TAG, msg);
        }
    }

    public static void d(String tag, String msg) {
        if (isDebug) {
            Log.d(tag, msg);
        }
    }

    public static void i(String tag, String msg) {
        if (isDebug) {
            Log.i(tag, msg);
        }
    }

    public static void w(String tag, String msg) {
        if (isDebug) {
            Log.w(tag, msg);
        }
    }
 public static void w(String msg) {
        if (isDebug) {
            Log.w(DEFAULT_TAG+"_Exception", msg);
        }
    }

    private final static X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");

    /**
     * 判断是否打包
     *
     * @param ctx
     * @return true 没打包 false 签名打包
     */
    public static boolean isDebuggable(Context ctx) {
        boolean debuggable = false;
        try {
            PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
            Signature signatures[] = pinfo.signatures;
            for (int i = 0; i < signatures.length; i++) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
                X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
                debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
                if (debuggable)
                    break;
            }
        } catch (NameNotFoundException | CertificateException ignore) {
        }
        return debuggable;
    }


}
